<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>任务模板管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增模板
            </el-button>
            <el-button type="success" @click="handleImport">
              <el-icon><Upload /></el-icon>
              导入模板
            </el-button>
            <el-button type="info" @click="handleExport" :disabled="!ids.length">
              <el-icon><Download /></el-icon>
              导出模板
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="模板名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入模板名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable style="width: 150px">
              <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable style="width: 120px">
              <el-option label="低" value="LOW" />
              <el-option label="中" value="MEDIUM" />
              <el-option label="高" value="HIGH" />
              <el-option label="紧急" value="URGENT" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="模板名称" align="left" min-width="200">
          <template #default="scope">
            <div>
              <div class="template-title">{{ scope.row.name }}</div>
              <div class="text-muted">{{ scope.row.description || '暂无描述' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" width="120">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.categoryName || '未分类' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="优先级" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityTagType(scope.row.priority)">
              {{ getPriorityText(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="预估工时" align="center" width="100">
          <template #default="scope">
            <span>{{ scope.row.estimatedHours || 0 }}小时</span>
          </template>
        </el-table-column>
        <el-table-column label="使用次数" align="center" width="100">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.usageCount || 0 }}次</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" icon="View" @click="handleView(scope.row)" link>查看</el-button>
            <el-button type="primary" icon="Edit" @click="handleUpdate(scope.row)" link>编辑</el-button>
            <el-button type="success" icon="Plus" @click="handleCreateTask(scope.row)" link>创建任务</el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" style="margin-left: 10px">
              <el-button type="primary" link>
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleCopy" icon="DocumentCopy">复制模板</el-dropdown-item>
                  <el-dropdown-item command="handleExportSingle" icon="Download">导出模板</el-dropdown-item>
                  <el-dropdown-item command="handleDelete" icon="Delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改模板对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="templateFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入模板描述"
            :rows="3"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="低" value="LOW" />
                <el-option label="中" value="MEDIUM" />
                <el-option label="高" value="HIGH" />
                <el-option label="紧急" value="URGENT" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预估工时" prop="estimatedHours">
              <el-input-number v-model="form.estimatedHours" :min="0.5" :max="999" :step="0.5" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            placeholder="请输入任务内容模板"
            :rows="5"
          />
        </el-form-item>
        <el-form-item label="验收标准" prop="acceptanceCriteria">
          <el-input
            v-model="form.acceptanceCriteria"
            type="textarea"
            placeholder="请输入验收标准"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 从模板创建任务对话框 -->
    <el-dialog title="从模板创建任务" v-model="createTaskDialogVisible" width="600px" append-to-body>
      <el-form ref="createTaskFormRef" :model="createTaskForm" :rules="createTaskRules" label-width="100px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="createTaskForm.title" placeholder="请输入任务标题" />
        </el-form-item>
        <el-form-item label="指派给" prop="assigneeId">
          <el-select v-model="createTaskForm.assigneeId" placeholder="请选择执行人" style="width: 100%">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.nickname || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="createTaskForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endTime">
              <el-date-picker
                v-model="createTaskForm.endTime"
                type="datetime"
                placeholder="选择截止时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="createTaskForm.note"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createTaskDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCreateTask">创建任务</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TaskTemplate">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Download, Search, Refresh, View, Edit, DocumentCopy, Delete } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import {
  getTaskTemplatePage,
  getTaskTemplateDetail,
  createTaskTemplate,
  updateTaskTemplate,
  deleteTaskTemplate,
  createTaskFromTemplate,
  getTaskCategoryTree
} from '@/api/task'
import { getUserList } from '@/api/user'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const open = ref(false)
const createTaskDialogVisible = ref(false)
const title = ref('')
const queryRef = ref()
const templateFormRef = ref()
const createTaskFormRef = ref()

// 列表数据
const templateList = ref([])
const categoryList = ref([])
const userList = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  categoryId: undefined,
  priority: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  name: undefined,
  description: undefined,
  categoryId: undefined,
  priority: 'MEDIUM',
  estimatedHours: 8,
  status: 1,
  content: undefined,
  acceptanceCriteria: undefined,
  tags: undefined
})

// 创建任务表单数据
const createTaskForm = reactive({
  templateId: undefined,
  title: undefined,
  assigneeId: undefined,
  startTime: undefined,
  endTime: undefined,
  note: undefined
})

// 表单校验规则
const rules = reactive({
  name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  estimatedHours: [{ required: true, message: '预估工时不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '任务内容不能为空', trigger: 'blur' }]
})

// 创建任务表单校验规则
const createTaskRules = reactive({
  title: [{ required: true, message: '任务标题不能为空', trigger: 'blur' }],
  assigneeId: [{ required: true, message: '请选择执行人', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择截止时间', trigger: 'change' }]
})

// 获取模板列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getTaskTemplatePage(queryParams)
    if (response.code === 200) {
      templateList.value = response.data.rows || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取模板列表失败')
    }
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')

    // 模拟数据
    templateList.value = [
      {
        id: 1,
        name: '前端开发任务模板',
        description: '用于前端功能开发的标准任务模板',
        categoryId: 'cat001',
        categoryName: '开发类',
        priority: 'HIGH',
        estimatedHours: 16,
        usageCount: 25,
        status: 1,
        content: '1. 需求分析\n2. 界面设计\n3. 功能开发\n4. 测试验证\n5. 代码审查',
        acceptanceCriteria: '1. 功能正常运行\n2. 界面美观\n3. 代码规范\n4. 通过测试',
        tags: '前端,开发,Vue',
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        name: '后端API开发模板',
        description: '用于后端API接口开发的标准模板',
        categoryId: 'cat001',
        categoryName: '开发类',
        priority: 'MEDIUM',
        estimatedHours: 12,
        usageCount: 18,
        status: 1,
        content: '1. 接口设计\n2. 数据库设计\n3. 业务逻辑开发\n4. 接口测试\n5. 文档编写',
        acceptanceCriteria: '1. 接口功能完整\n2. 性能达标\n3. 文档完善\n4. 通过测试',
        tags: '后端,API,Spring Boot',
        createTime: '2024-01-15 11:20:00'
      },
      {
        id: 3,
        name: '测试用例编写模板',
        description: '用于编写测试用例的标准模板',
        categoryId: 'cat002',
        categoryName: '测试类',
        priority: 'LOW',
        estimatedHours: 6,
        usageCount: 12,
        status: 1,
        content: '1. 测试计划制定\n2. 用例设计\n3. 用例编写\n4. 用例评审\n5. 用例执行',
        acceptanceCriteria: '1. 覆盖率达标\n2. 用例清晰\n3. 可执行性强\n4. 通过评审',
        tags: '测试,用例,质量',
        createTime: '2024-01-15 14:15:00'
      }
    ]
    total.value = 3
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    const response = await getTaskCategoryTree()
    if (response.code === 200) {
      categoryList.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // 模拟数据
    categoryList.value = [
      { id: 'cat001', name: '开发类' },
      { id: 'cat002', name: '测试类' },
      { id: 'cat003', name: '设计类' },
      { id: 'cat004', name: '运维类' }
    ]
  }
}

// 获取用户列表
const getUsersList = async () => {
  try {
    const response = await getUserList({ pageNum: 1, pageSize: 100 })
    if (response.code === 200) {
      userList.value = response.data.rows || []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    // 模拟数据
    userList.value = [
      { id: 'user001', username: 'admin', nickname: '管理员' },
      { id: 'user002', username: 'developer1', nickname: '开发者1' },
      { id: 'user003', username: 'tester1', nickname: '测试员1' }
    ]
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加任务模板'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  Object.assign(form, row)
  open.value = true
  title.value = '修改任务模板'
}

// 查看按钮操作
const handleView = (row) => {
  ElMessageBox.alert(
    `<div style="text-align: left;">
      <p><strong>模板名称：</strong>${row.name}</p>
      <p><strong>描述：</strong>${row.description || '暂无'}</p>
      <p><strong>分类：</strong>${row.categoryName}</p>
      <p><strong>优先级：</strong>${getPriorityText(row.priority)}</p>
      <p><strong>预估工时：</strong>${row.estimatedHours}小时</p>
      <p><strong>使用次数：</strong>${row.usageCount}次</p>
      <p><strong>任务内容：</strong></p>
      <pre style="white-space: pre-wrap; background: #f5f7fa; padding: 10px; border-radius: 4px;">${row.content || '暂无'}</pre>
      <p><strong>验收标准：</strong></p>
      <pre style="white-space: pre-wrap; background: #f5f7fa; padding: 10px; border-radius: 4px;">${row.acceptanceCriteria || '暂无'}</pre>
      <p><strong>标签：</strong>${row.tags || '暂无'}</p>
    </div>`,
    '模板详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  )
}

// 从模板创建任务
const handleCreateTask = (row) => {
  createTaskForm.templateId = row.id
  createTaskForm.title = row.name
  createTaskDialogVisible.value = true
}

// 状态修改
const handleStatusChange = async (row) => {
  const text = row.status === 1 ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.name + '"模板吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await updateTaskTemplate(row.id, { status: row.status })
    if (response.code === 200) {
      ElMessage.success(text + '成功')
    } else {
      ElMessage.error(response.message || text + '失败')
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    if (error !== 'cancel') {
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(text + '失败')
    }
  }
}

// 导入模板
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 导出模板
const handleExport = () => {
  if (!ids.value.length) {
    ElMessage.warning('请选择要导出的模板')
    return
  }
  ElMessage.info('导出功能开发中')
}

// 下拉菜单操作
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleCopy':
      handleCopy(row)
      break
    case 'handleExportSingle':
      handleExportSingle(row)
      break
    case 'handleDelete':
      handleDelete(row)
      break
  }
}

// 复制模板
const handleCopy = async (row) => {
  try {
    await ElMessageBox.confirm('确定要复制该模板吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const copyData = {
      ...row,
      name: row.name + ' - 副本',
      id: undefined
    }

    const response = await createTaskTemplate(copyData)
    if (response.code === 200) {
      ElMessage.success('复制成功')
      getList()
    } else {
      ElMessage.error(response.message || '复制失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('复制失败:', error)
      ElMessage.error('复制失败')
    }
  }
}

// 导出单个模板
const handleExportSingle = (row) => {
  ElMessage.info('导出功能开发中')
}

// 删除按钮操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除模板"' + row.name + '"吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteTaskTemplate(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    name: undefined,
    description: undefined,
    categoryId: undefined,
    priority: 'MEDIUM',
    estimatedHours: 8,
    status: 1,
    content: undefined,
    acceptanceCriteria: undefined,
    tags: undefined
  })
  templateFormRef.value?.resetFields()
}

// 提交表单
const submitForm = () => {
  templateFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          const response = await updateTaskTemplate(form.id, form)
          if (response.code === 200) {
            ElMessage.success('修改成功')
          } else {
            ElMessage.error(response.message || '修改失败')
            return
          }
        } else {
          const response = await createTaskTemplate(form)
          if (response.code === 200) {
            ElMessage.success('新增成功')
          } else {
            ElMessage.error(response.message || '新增失败')
            return
          }
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 提交创建任务
const submitCreateTask = () => {
  createTaskFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const response = await createTaskFromTemplate(createTaskForm.templateId, createTaskForm)
        if (response.code === 200) {
          ElMessage.success('任务创建成功')
          createTaskDialogVisible.value = false
          // 重置表单
          Object.assign(createTaskForm, {
            templateId: undefined,
            title: undefined,
            assigneeId: undefined,
            startTime: undefined,
            endTime: undefined,
            note: undefined
          })
        } else {
          ElMessage.error(response.message || '任务创建失败')
        }
      } catch (error) {
        console.error('任务创建失败:', error)
        ElMessage.error('任务创建失败')
      }
    }
  })
}

// 工具函数
const getPriorityText = (priority) => {
  const priorityMap = {
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高',
    'URGENT': '紧急'
  }
  return priorityMap[priority] || '未知'
}

const getPriorityTagType = (priority) => {
  const typeMap = {
    'LOW': 'info',
    'MEDIUM': 'success',
    'HIGH': 'warning',
    'URGENT': 'danger'
  }
  return typeMap[priority] || 'info'
}

const parseTime = (time, pattern = '{y}-{m}-{d} {h}:{i}:{s}') => {
  if (!time) return ''
  return time
}

// 页面加载
onMounted(() => {
  getCategoryList()
  getUsersList()
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.template-title {
  font-weight: 500;
  color: #303133;
}

.dialog-footer {
  text-align: right;
}

// 分页组件样式
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: right;
}

// 消息框样式
:deep(.el-message-box__content) {
  max-height: 400px;
  overflow-y: auto;
}
</style>
